import path, { resolve } from "path";
import { app } from "electron";
import { exec, execFile, readFile } from "../../promisify-api.js";
import { spawn } from "child_process";
import iconv from 'iconv-lite'
import {getResourcesPath} from '../../utils.js';

const isMac = process.platform === "darwin"; // 获取当前运行平台
const resourcesPath = getResourcesPath();// 额外资源打包完的路径resources

const signApkWin = async (filePath, carType, win) => {
  const scriptPath = path.join(resourcesPath, "shell", "re-signer.ps1");
  const arg = [
    "-ExecutionPolicy",
    "Bypass",
    "-File",
    scriptPath,
    filePath,
    carType,
  ];
  const option = {
    shell: true,
  };
  const child = spawn("powershell", arg, option);

  const sendMsg = (status, output) => {
    const params = {
      status: status,
      data: {
        id: child.pid,
        msg: output,
      },
    };
    win.webContents.send("processMsg", params);
  };

  let finalRes;

  // 捕获标准输出
  child.stdout.on("data", (output) => {
    const outputStr =iconv.decode(output, "cp936");
    sendMsg(1, outputStr);
    const match = outputStr.match(/file>>>(.*?)<<<file/);
    match && (finalRes = match[1]);
  });

  // 捕获标准错误输出
  child.stderr.on("data", (output) => {
    const outputStr =iconv.decode(output, "cp936");
    sendMsg(0, outputStr);
  });

  // 当子进程结束时，会触发 'close' 事件
  child.on("close", (output) => {
    sendMsg(2, finalRes);
  });
};

const signApkMac = async (filePath, carType, win) => {
 
  
  const scriptPath = path.join(resourcesPath, "shell", "re-signer.sh");
  console.log(resourcesPath,scriptPath);
  const arg = [filePath, carType];
  const child = spawn(scriptPath, arg, { shell: true });

  const sendMsg = (status, output) => {
    const params = {
      status: status,
      data: {
        id: child.pid,
        msg: output,
      },
    };
    win.webContents.send("processMsg", params);
  };

  let finalRes;

  // 捕获标准输出
  child.stdout.on("data", (output) => {
    const outputStr = output.toString();
    sendMsg(1, outputStr);
    const match = outputStr.match(/file>>>(.*?)<<<file/);
    match && (finalRes = match[1]);
  });

  // 捕获标准错误输出
  child.stderr.on("data", (output) => {
    sendMsg(0, output.toString());
  });

  // 当子进程结束时，会触发 'close' 事件
  child.on("close", (output) => {
    sendMsg(2, finalRes);
  });
};

export const signApk = async (filePath, carType, win) => {
  // 签名apk
  if (isMac) {
    return signApkMac(filePath, carType, win);
  } else {
    return signApkWin(filePath, carType, win);
  }
};

const reverseApkMac = async (filePath, pkgName, win) => {
  return new Promise(async (resolve, reject) => {
    const scriptPath = path.join(resourcesPath, "shell", "change-pkg.sh");
    await exec("chmod 777 " + scriptPath);

    const arg = [filePath, pkgName, resourcesPath];
    const child = spawn(scriptPath, arg, { shell: true });

    const sendMsg = (status, output) => {
      const params = {
        status: status,
        data: {
          id: child.pid,
          msg: output,
        },
      };
      win.webContents.send("processMsg", params);
    };

    let finalRes;

    // 捕获标准输出
    child.stdout.on("data", (output) => {
      const outputStr = output.toString();
      sendMsg(1, outputStr);
      const match = outputStr.match(/file>>>(.*?)<<<file/);
      match && (finalRes = match[1]);
    });

    // 捕获标准错误输出
    child.stderr.on("data", (output) => {
      sendMsg(0, output.toString());
    });

    // 当子进程结束时，会触发 'close' 事件
    child.on("close", (output) => {
      resolve(finalRes);
      // sendMsg(2, finalRes);
    });
  });
};

const reverseApkWin = (filePath, pkgName, win) => {
  return new Promise(async (resolve, reject) => {
    const scriptPath = path.join(resourcesPath, "shell", "change-pkg.ps1");
    const arg = [
      "-ExecutionPolicy",
      "Bypass",
      "-File",
      scriptPath,
      filePath,
      pkgName,
      resourcesPath,
    ];
    const child = spawn("powershell", arg, { shell: true });
    const sendMsg = (status, output) => {
      const params = {
        status: status,
        data: {
          id: child.pid,
          msg: output,
        },
      };
      win.webContents.send("processMsg", params);
    };

    let finalRes;

    // 捕获标准输出
    child.stdout.on("data", (output) => {
      const outputStr =iconv.decode(output, "cp936");
      sendMsg(1, outputStr);
      const match = outputStr.match(/file>>>(.*?)<<<file/);
      match && (finalRes = match[1]);
    });

    // 捕获标准错误输出
    child.stderr.on("data", (output) => {
      const outputStr =iconv.decode(output, "cp936");
      sendMsg(0, outputStr);
    });

    // 当子进程结束时，会触发 'close' 事件
    child.on("close", (output) => {
      resolve(finalRes);
      // sendMsg(2, finalRes);
    });
  });
};

export const reverseApk = async (filePath, params, win) => {
  if (isMac) {
    return reverseApkMac(filePath, params, win);
  } else {
    return reverseApkWin(filePath, params, win);
  }
};

// 破解apk，使其可以安装到车机上，这是总入口
export const crackApk = async ({ filePath, carType, pkgName }) => {
  const win = global.app.mainWindow;
  let apkPath = filePath;
  if (pkgName) {
    // 如果选择了报名，需要进行改包名的操作
    apkPath = await reverseApk(filePath, pkgName, win);
  }
  apkPath = await signApk(apkPath, carType, win);
  return { code: 1, data: { path: apkPath } };
};
